<template>
  <div class="volunteerList-wrapper">
    <div class="header">
      <div
        :class="['header-item', 'item' + index]"
        v-for="(item, index) in headerList"
        :key="index"
        :style="{
          width: item?.width,
          textAlign: item?.textAlign,
          padding: item?.padding,
        }"
      >
        {{ item.label }}
      </div>
    </div>
    <div
      class="table-container border-left border-top"
      v-if="schoolList.length > 0"
    >
      <VueDraggable
        v-model="schoolList"
        animation="150"
        @end="onFirstLevelEnd"
        group="father"
        chosen-class="chosen"
        :force-fallback="true"
        handle=".first-drag-element"
      >
        <div
          class="table-item"
          v-for="(item, index) in schoolList"
          :key="index"
        >
          <div
            :class="{
              'father-level': true,
              extended: item.showSonLevel,
              'moving-to-top': item.isMovingToTop,
            }"
            v-if="item.collegeInfo"
          >
            <div
              class="first-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              志愿{{ index + 1 }}
              <img
                :class="['icon', item.showSonLevel ? 'rotate' : '']"
                :src="item.showSonLevel ? unSpread : spread"
              />
              <span class="tips" :class="{ active: item.showSonLevel }">{{
                item.showSonLevel ? '收起' : '展开'
              }}</span>
            </div>
            <div
              class="second-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              <div
                class="label match-rate-bg"
                :class="[
                  item.matchRate > 79
                    ? 'high'
                    : item.matchRate > 49
                    ? 'medium'
                    : 'low',
                ]"
              >
                {{
                  item.matchRate > 79 ? '保' : item.matchRate > 49 ? '稳' : '冲'
                }}
              </div>

              <div :class="item.matchRate ? '' : 'center-span'">
                <span class="match-rate">{{ item.matchRate || '-' }}</span>
                <span class="question" v-if="item.matchRate">%</span>
              </div>

              <div v-if="item.matchRate" class="risk">
                {{
                  item.matchRate > 79
                    ? '较低风险'
                    : item.matchRate > 64
                    ? '中低风险'
                    : item.matchRate > 49
                    ? '中等风险'
                    : '较高风险'
                }}
              </div>
            </div>
            <div class="third-column border-right border-bottom">
              <div class="top" @click="handleToSchoolDetail(item)">
                <img
                  :src="item.collegeInfo.icon"
                  class="school-avator"
                  alt=""
                />
                <div class="name">
                  {{ item.collegeInfo.name }}{{ item.groupName }}
                </div>
              </div>
              <div class="middle" @click="foldSonLevel(item, index)">
                {{ item.collegeInfo.dualClassName.replace(/,/g, ' / ') }}
              </div>

              <div class="bottom" @click="foldSonLevel(item, index)">
                {{ item.collegeInfo.collegeType }}/{{
                  item.collegeInfo.natureName
                }}<span>|</span>{{ item.collegeInfo.cityName
                }}<span>|</span>院校招生代码：{{ item?.enrolCode || '-' }}
              </div>
            </div>
            <div
              class="fourth-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              <div class="num">
                <span>{{ item.plannedNum }}</span
                >人
              </div>
              <div class="subject">
                {{ getSubjectShortName(item.limitSubject) }}
              </div>
            </div>
            <div
              class="fifth-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              <div
                class="fifth-column-item"
                v-for="(item, ele_index) in thirdColumnLabelList"
                :key="ele_index"
              >
                {{ item }}
                <div
                  class="tooltip-wrapper"
                  v-if="item == '最低分与省控线的差距'"
                >
                  <img
                    v-if="item == '最低分与省控线的差距'"
                    :src="questionLogo"
                    class="question-icon"
                    @click.stop="showTooltip(1, item.volunteerId)"
                  />
                  <div
                    class="tooltip-content"
                    v-if="tooltipStates[`${item.volunteerId}-1`]"
                  >
                    专业组里的最低分与省控线差距大，录取概率相对较低。专业组里的最低分与省控线差距小，录取概率相对较高。
                  </div>
                </div>
                <div class="tooltip-wrapper" v-if="item == '我的排名竞争力'">
                  <img
                    v-if="item == '我的排名竞争力'"
                    class="question-icon"
                    :src="questionLogo"
                    @click.stop="showTooltip(2, item.volunteerId)"
                  />
                  <div
                    class="tooltip-content"
                    v-if="tooltipStates[`${item.volunteerId}-2`]"
                  >
                    反映了考生当前成绩在当前院校的竞争力高低，等效位差只用于参考位次在历年竞争力情况，选择志愿时参考录取概率进行填报。
                  </div>
                </div>
              </div>
            </div>
            <div
              class="sixth-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              <template v-if="item.previousData[0]">
                <div class="sixth-column-item">
                  {{ item.previousData[0].admissionNum || '-' }}
                </div>
                <div class="sixth-column-item">
                  {{ item.previousData[0].lineDiffNum || '-' }}
                </div>
                <div class="sixth-column-item">
                  {{ item.previousData[0].minScore || '-' }}
                </div>
                <div class="sixth-column-item">
                  {{ item.previousData[0].minRank || '-' }}
                </div>
                <div class="sixth-column-item">
                  <template v-if="item.previousData[0]">
                    <span
                      :style="{
                        color:
                          item.previousData[0].competenceNum > 0
                            ? '#11B414'
                            : '#F76D32',
                      }"
                      >{{
                        item.previousData[0].competenceNum > 0
                          ? '高'
                          : item.previousData[0].competenceNum < 0
                          ? '低'
                          : ''
                      }}{{
                        item.previousData[0].competenceNum == null
                          ? '-'
                          : Math.abs(item.previousData[0].competenceNum) == 0 &&
                            item.previousData[0].competenceNum != null
                          ? '持平'
                          : Math.abs(item.previousData[0].competenceNum)
                      }}</span
                    >
                  </template>
                  <template v-else>
                    <div class="sixth-column-item no-data">-</div>
                  </template>
                </div>
              </template>
              <template v-else>
                <div class="sixth-column-item no-data">-</div>
              </template>
            </div>
            <div
              class="seventh-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              <template v-if="item.previousData[1]">
                <div class="seventh-column-item">
                  {{ item.previousData[1]?.admissionNum || '-' }}
                </div>
                <div class="seventh-column-item">
                  {{ item.previousData[1]?.lineDiffNum || '-' }}
                </div>
                <div class="seventh-column-item">
                  {{ item.previousData[1]?.minScore || '-' }}
                </div>
                <div class="seventh-column-item">
                  {{ item.previousData[1]?.minRank || '-' }}
                </div>
                <div class="seventh-column-item">
                  <template v-if="item.previousData[1]">
                    <span
                      :style="{
                        color:
                          item.previousData[1].competenceNum > 0
                            ? '#11B414'
                            : '#F76D32',
                      }"
                      >{{
                        item.previousData[1].competenceNum > 0
                          ? '高'
                          : item.previousData[1].competenceNum < 0
                          ? '低'
                          : ''
                      }}{{
                        item.previousData[1].competenceNum == null
                          ? '-'
                          : Math.abs(item.previousData[1].competenceNum) == 0 &&
                            item.previousData[1].competenceNum != null
                          ? '持平'
                          : Math.abs(item.previousData[1].competenceNum)
                      }}</span
                    >
                  </template>
                  <template v-else>
                    <div class="seventh-column-item no-data">-</div>
                  </template>
                </div>
              </template>
              <template v-else>
                <div class="seventh-column-item no-data">-</div>
              </template>
            </div>
            <div
              class="eighth-column border-right border-bottom"
              @click="foldSonLevel(item, index)"
            >
              <template v-if="item.previousData[2]">
                <div class="eighth-column-item">
                  {{ item.previousData[2].admissionNum || '-' }}
                </div>
                <div class="eighth-column-item">
                  {{ item.previousData[2].lineDiffNum || '-' }}
                </div>
                <div class="eighth-column-item">
                  {{ item.previousData[2].minScore || '-' }}
                </div>
                <div class="eighth-column-item">
                  {{ item.previousData[2].minRank || '-' }}
                </div>
                <div class="eighth-column-item">
                  <span
                    :style="{
                      color:
                        item.previousData[2].competenceNum > 0
                          ? '#11B414'
                          : '#F76D32',
                    }"
                    >{{
                      item.previousData[2].competenceNum > 0
                        ? '高'
                        : item.previousData[2].competenceNum < 0
                        ? '低'
                        : ''
                    }}{{
                      item.previousData[2].competenceNum == null
                        ? '-'
                        : Math.abs(item.previousData[2].competenceNum) == 0 &&
                          item.previousData[2].competenceNum != null
                        ? '持平'
                        : Math.abs(item.previousData[2].competenceNum)
                    }}</span
                  >
                </div>
              </template>
              <template v-else>
                <div class="eighth-column-item no-data">-</div>
              </template>
            </div>
            <div class="ninth-column border-right border-bottom">
              <div
                class="ninth-column-item"
                v-if="index !== 0"
                @click="handleSetTop(item, index)"
              >
                <img :src="setTopIcon" class="icon" />
                <span>置顶</span>
              </div>
              <div class="ninth-column-item first-drag-element">
                <img :src="dragIcon" class="icon" />
                <span>移动</span>
              </div>
              <div
                class="ninth-column-item"
                @click="handleVolunteerDelete(item)"
              >
                <img :src="deleteIcon" class="icon" />
                <span>删除</span>
              </div>
            </div>
          </div>
          <!-- 父级没有collegeInfo的情况下，就显示添加按钮 -->
          <div class="add-level" v-if="!item.collegeInfo">
            <div class="index-column border-right border-bottom">
              志愿{{ index + 1 }}
            </div>
            <div class="add-column border-right border-bottom">
              <div
                class="add-column-item border-primary"
                @click="handleFatherAddClick"
              >
                添加
              </div>
            </div>
          </div>
          <transition name="slide">
            <div v-if="item.showSonLevel">
              <VueDraggable
                v-model="item.children"
                @end="(e) => onSonLevelDragEnd(e, item)"
                group="son"
                chosen-class="chosen"
                :force-fallback="true"
                handle=".second-drag-element"
              >
                <template v-for="(_item, _index) in item.children">
                  <div
                    class="son-level"
                    :key="_item.cpgId || _index"
                    :class="{ 'no-border': _index == item.children.length - 1 }"
                    v-if="_item.showContent"
                  >
                    <div class="first-column border-right border-bottom">
                      专业{{ _index + 1 }}
                    </div>
                    <div class="second-column border-right border-bottom">
                      <div
                        v-if="_item.matchRate"
                        :class="[
                          'label',
                          _item.matchRate > 79
                            ? 'success'
                            : _item.matchRate > 49
                            ? 'warning'
                            : 'danger',
                        ]"
                      >
                        {{
                          _item.matchRate > 79
                            ? '保'
                            : _item.matchRate > 49
                            ? '稳'
                            : '冲'
                        }}
                      </div>
                      <div :class="_item.matchRate ? '' : 'center-span'">
                        <span class="match-rate">{{
                          _item.matchRate || '-'
                        }}</span>
                        <span class="question" v-if="_item.matchRate">%</span>
                      </div>

                      <div class="risk" v-if="_item.matchRate">
                        {{
                          _item.matchRate > 79
                            ? '较低风险'
                            : _item.matchRate > 64
                            ? '中低风险'
                            : _item.matchRate > 49
                            ? '中等风险'
                            : '较高风险'
                        }}
                      </div>
                    </div>
                    <div class="third-column border-right border-bottom">
                      <div class="top">
                        <div class="name">
                          {{ _item.groupName }}
                        </div>
                      </div>
                      <div class="middle">
                        {{ _item.showContent }}
                      </div>
                      <div class="bottom" v-if="_item.proCode">
                        {{ '招生代码：' + _item.proCode }}
                      </div>
                    </div>
                    <div class="fourth-column border-right border-bottom">
                      <div class="num">
                        <span>{{ _item.plannedNum }}</span
                        >人
                      </div>
                      <div class="subject">
                        {{ getSubjectShortName(_item.limitSubject) }}
                      </div>
                    </div>
                    <div class="fifth-column border-right border-bottom">
                      <div
                        class="fifth-column-item"
                        v-for="(item, ele_index) in thirdColumnLabelListForSon"
                        :key="ele_index"
                      >
                        {{ item }}
                        <div
                          class="tooltip-wrapper"
                          v-if="item == '最低分与省控线的差距'"
                        >
                          <img
                            v-if="item == '最低分与省控线的差距'"
                            :src="questionLogo"
                            class="question-icon"
                            @click.stop="showTooltip(1, _item.volunteerId)"
                          />
                          <div
                            class="tooltip-content"
                            v-if="tooltipStates[`${_item.volunteerId}-1`]"
                          >
                            专业组里的最低分与省控线差距大，录取概率相对较低。专业组里的最低分与省控线差距小，录取概率相对较高。
                          </div>
                        </div>
                        <div
                          class="tooltip-wrapper"
                          v-if="item == '我的排名竞争力'"
                        >
                          <img
                            v-if="item == '我的排名竞争力'"
                            class="question-icon"
                            :src="questionLogo"
                            @click.stop="showTooltip(2, _item.volunteerId)"
                          />
                          <div
                            class="tooltip-content"
                            v-if="tooltipStates[`${_item.volunteerId}-2`]"
                          >
                            反映了考生当前成绩在当前院校的竞争力高低，等效位差只用于参考位次在历年竞争力情况，选择志愿时参考录取概率进行填报。
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="sixth-column border-right border-bottom">
                      <template v-if="_item.previousData[0]">
                        <div class="sixth-column-item">
                          {{ _item.previousData[0].admissionNum || '' }}
                        </div>
                        <div class="sixth-column-item">
                          {{ _item.previousData[0].lineDiffNum || '-' }}
                        </div>
                        <div class="sixth-column-item">
                          {{ _item.previousData[0].minScore || '-' }}
                        </div>
                        <div class="sixth-column-item">
                          {{ _item.previousData[0].minRank || '-' }}
                        </div>
                        <div class="sixth-column-item">
                          <span
                            :style="{
                              color:
                                _item.previousData[0].competenceNum > 0
                                  ? '#11B414'
                                  : '#F76D32',
                            }"
                            >{{
                              _item.previousData[0].competenceNum > 0
                                ? '高'
                                : _item.previousData[0].competenceNum < 0
                                ? '低'
                                : ''
                            }}{{
                              _item.previousData[0].competenceNum == null
                                ? '-'
                                : Math.abs(
                                    _item.previousData[0].competenceNum
                                  ) == 0 &&
                                  _item.previousData[0].competenceNum != null
                                ? '持平'
                                : Math.abs(_item.previousData[0].competenceNum)
                            }}</span
                          >
                        </div>
                      </template>
                      <template v-else>
                        <div class="sixth-column-item no-data">-</div>
                      </template>
                    </div>
                    <div class="seventh-column border-right border-bottom">
                      <template v-if="_item.previousData[1]">
                        <div class="seventh-column-item">
                          {{ _item.previousData[1].admissionNum || '-' }}
                        </div>
                        <div class="seventh-column-item">
                          {{ _item.previousData[1].lineDiffNum || '-' }}
                        </div>
                        <div class="seventh-column-item">
                          {{ _item.previousData[1].minScore || '-' }}
                        </div>
                        <div class="seventh-column-item">
                          {{ _item.previousData[1].minRank || '-' }}
                        </div>
                        <div class="seventh-column-item">
                          <span
                            :style="{
                              color:
                                _item.previousData[1].competenceNum > 0
                                  ? '#11B414'
                                  : '#F76D32',
                            }"
                            >{{
                              _item.previousData[1].competenceNum > 0
                                ? '高'
                                : _item.previousData[1].competenceNum < 0
                                ? '低'
                                : ''
                            }}{{
                              _item.previousData[1].competenceNum == null
                                ? '-'
                                : Math.abs(
                                    _item.previousData[1].competenceNum
                                  ) == 0 &&
                                  _item.previousData[1].competenceNum != null
                                ? '持平'
                                : Math.abs(_item.previousData[1].competenceNum)
                            }}</span
                          >
                        </div>
                      </template>
                      <template v-else>
                        <div class="seventh-column-item no-data">-</div>
                      </template>
                    </div>
                    <div class="eighth-column border-right border-bottom">
                      <template v-if="_item.previousData[2]">
                        <div class="eighth-column-item">
                          {{ _item.previousData[2].admissionNum || '-' }}
                        </div>
                        <div class="eighth-column-item">
                          {{ _item.previousData[2].lineDiffNum || '-' }}
                        </div>
                        <div class="eighth-column-item">
                          {{ _item.previousData[2].minScore || '-' }}
                        </div>
                        <div class="eighth-column-item">
                          {{ _item.previousData[2].minRank || '-' }}
                        </div>
                        <div class="eighth-column-item">
                          <span
                            :style="{
                              color:
                                _item.previousData[2].competenceNum > 0
                                  ? '#11B414'
                                  : '#F76D32',
                            }"
                            >{{
                              _item.previousData[2].competenceNum > 0
                                ? '高'
                                : _item.previousData[2].competenceNum < 0
                                ? '低'
                                : ''
                            }}{{
                              _item.previousData[2].competenceNum == null
                                ? '-'
                                : Math.abs(
                                    _item.previousData[2].competenceNum
                                  ) == 0 &&
                                  _item.previousData[2].competenceNum != null
                                ? '持平'
                                : Math.abs(_item.previousData[2].competenceNum)
                            }}</span
                          >
                        </div>
                      </template>
                      <template v-else>
                        <div class="eighth-column-item no-data">-</div>
                      </template>
                    </div>
                    <div class="ninth-column border-right border-bottom">
                      <div
                        class="ninth-column-item"
                        v-if="_index !== 0"
                        @click="handleSonSetTop(_item, _index, item)"
                      >
                        <img :src="setTopIcon" class="icon" />
                        <span>置顶</span>
                      </div>
                      <div class="ninth-column-item second-drag-element">
                        <img :src="dragIcon" class="icon" />
                        <span>移动</span>
                      </div>
                      <div
                        class="ninth-column-item"
                        @click="handleVolunteerDelete(_item)"
                      >
                        <img :src="deleteIcon" class="icon" />
                        <span>删除</span>
                      </div>
                    </div>
                  </div>
                  <div v-else class="add-level add-son" :key="_item.cpgId">
                    <div class="index-column border-right border-bottom">
                      专业 {{ _index + 1 }}
                    </div>
                    <div class="add-column border-right border-bottom">
                      <div
                        class="add-column-item border-primary"
                        @click="handleChildrenAddClick(item)"
                      >
                        添加
                      </div>
                    </div>
                  </div>
                </template>
              </VueDraggable>
            </div>
          </transition>
        </div>
      </VueDraggable>
    </div>
    <PickVolunteerMajorPopup
      v-model:visible="pickMajorDialogVisible"
      v-model:currentCollegeItem="currentCollegeItem"
      @refreshData="getVolunteerGroupListFn"
    />
    <ConfirmDialog
      v-model:show="deleteDialogVisible"
      title="温馨提示"
      message="是否确认删除？"
      @confirm="handleVolunteerDeleteConfirm"
    />
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  watch,
  onUnmounted,
  computed,
  defineExpose,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { VueDraggable } from 'vue-draggable-plus';
import { showConfirmDialog, showToast } from 'vant';
import { useVolunteerStore } from '@/store/volunteer';
import {
  volunteerSort,
  getVolunteerGroupList,
  volunteerDelete,
} from '@/api/volunteer';
import spread from '@/assets/images/spread.png';
import unSpread from '@/assets/images/unSpread.png';
import deleteIcon from '@/assets/images/deleteIcon.png';
import dragIcon from '@/assets/images/dragIcon.png';
import setTopIcon from '@/assets/images/setTop.png';
import PickVolunteerMajorPopup from '@/components/PickVolunteerMajorPopup.vue';
import ConfirmDialog from '@/components/ConfirmDialog.vue';
import { fill } from 'lodash-es';
import { getSubjectShortName } from '@/utils/subjectData';

const emit = defineEmits(['volunteerCurInfoFn']);

const router = useRouter();
const store = useVolunteerStore();

const props = defineProps({
  currentWishDetail: {
    type: Object,
    default: () => {},
  },
});

const route = useRoute();
const volunteerInfo = computed(() => store.volunteerInfo);

const planYear = volunteerInfo.value.planYear;

const headerList = [
  {
    label: '序号',
  },
  {
    label: '录取概率',
  },
  {
    label: '院校 - 专业组',
  },
  {
    label: '2024招生计划',
  },
  {
    label: '历年',
  },
  {
    label: '2024',
  },
  {
    label: '2023',
  },
  {
    label: '2022',
  },
  {
    label: '操作',
  },
];

const questionLogo =
  'https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/question.png';

const schoolList = ref([]);
const thirdColumnLabelList = [
  '录取人数',
  '最低分与省控线的差距',
  '录取最低分',
  '录取最低位次',
  '我的排名竞争力',
];
const thirdColumnLabelListForSon = [
  '录取人数',
  '最低分与省控线的差距',
  '最低分',
  '最低位次',
  '我的排名竞争力',
];

const handleToSchoolDetail = (item) => {
  router.push({
    path: '/schoolDetail',
    query: {
      dataId: item.collegeId,
      dataName: item.collegeInfo.name,
    },
  });
};

const onFirstLevelEnd = async (e) => {
  const newIndex = e.newIndex;
  const dragItem = schoolList.value[newIndex];
  const params = {
    volunteerId: dragItem.volunteerId,
    afterSort: newIndex + 1,
  };
  await volunteerSort(params);
};

const foldSonLevel = (item, index) => {
  if (item.showSonLevel == false) {
    getProGroupForSonListFn(item, index);
  } else {
    item.showSonLevel = false;
  }
  schoolList.value.forEach((item, ele_index) => {
    if (index != ele_index) {
      item.showSonLevel = false;
    }
  });
};

const getProGroupForSonListFn = async (item, index) => {
  const params = {
    volunteerId: item.volunteerId,
    regionId: props.currentWishDetail.regionId,
  };
  const res = await getVolunteerGroupList(params);
  if (res.code == 200) {
    if (res.data.length == 0) {
      showToast('暂无更多数据');
      return;
    }
    res.data.forEach((item) => {
      item.previousData = Array(3)
        .fill()
        .map(() => createDefaultYearData());
      if (item.yearData) {
        const firstYearData = item.yearData.find(
          (_item) => _item.year == defaultYear
        );
        item.previousData[0] = getYearData(firstYearData?.data);
        const secondYearData = item.yearData.find(
          (_item) => _item.year == defaultYear - 1
        );
        item.previousData[1] = getYearData(secondYearData?.data);
        const thirdYearData = item.yearData.find(
          (_item) => _item.year == defaultYear - 2
        );
        item.previousData[2] = getYearData(thirdYearData?.data);
      }
    });
    item.children = res.data; // TODO: 这里可能需要优化
    item.showSonLevel = !item.showSonLevel;
  }
};

const handleFatherAddClick = () => {
  router.push({
    path: '/collegeVolunteer',
  });
};

const deleteDialogVisible = ref(false);

const handleVolunteerDeleteConfirm = () => {
  const params = {
    volunteerId: deleteItem.volunteerId,
  };
  volunteerDelete(params).then((res) => {
    if (res.code == 200) {
      showToast('删除成功！');
      getVolunteerGroupListFn();
      emit('volunteerCurInfoFn');
    }
  });
};

let deleteItem = '';
const handleVolunteerDelete = (item) => {
  deleteItem = item;
  deleteDialogVisible.value = true;
};

const createDefaultYearData = () => ({
  admissionNum: '', // 录取人数
  lineDiffNum: '', // 最低分与省控线的差距
  minScore: '', // 最低录取分数
  minRank: '', // 录取最低位次
  competenceNum: null, //我的排名竞争力
});

// 获取去年的年份
const getLastYear = () => {
  const currentDate = new Date();
  return currentDate.getFullYear() - 1;
};

headerList[3].label = `${volunteerInfo.value.planYear}招生计划`;
const defaultYear = volunteerInfo.value.defaultYear || getLastYear();
headerList[5].label = defaultYear;
headerList[6].label = defaultYear - 1;
headerList[7].label = defaultYear - 2;

const getVolunteerGroupListFn = async () => {
  const params = {
    volunteerId: props.currentWishDetail.volunteerId,
    regionId: props.currentWishDetail.regionId,
  };
  const res = await getVolunteerGroupList(params);
  if (res.code == 200) {
    schoolList.value = res.data;
    schoolList.value.forEach((item) => {
      if (!item.collegeId) {
        return;
      }
      item.showSonLevel = false;
      item.isMovingToTop = false;
      item.previousData = Array(3)
        .fill()
        .map(() => createDefaultYearData());
      if (item.yearData) {
        const firstYearData = item.yearData.find(
          (_item) => _item.year == defaultYear
        );
        item.previousData[0] = getYearData(firstYearData?.data);
        const secondYearData = item.yearData.find(
          (_item) => _item.year == defaultYear - 1
        );
        item.previousData[1] = getYearData(secondYearData?.data);
        const thirdYearData = item.yearData.find(
          (_item) => _item.year == defaultYear - 2
        );
        item.previousData[2] = getYearData(thirdYearData?.data);
      }
    });
  }
};

watch(
  // TODO:目前存在的问题，手动刷新后getVolunteerGroupListFn不执行
  () => props.currentWishDetail,
  (newVal) => {
    getVolunteerGroupListFn();
  },
  { deep: true }
);

const keyList = [
  'admissionNum',
  'lineDiffNum',
  'minScore',
  'minRank',
  'competenceNum',
];
const getYearData = (data) => {
  if (!data) return null;
  const isNoData = keyList.every((key) => data[key] == null || data[key] == '');
  return isNoData ? null : data;
};

const onSonLevelDragEnd = async (e, fatherItem) => {
  const newIndex = e.newIndex;
  const dragItem = fatherItem.children[newIndex];
  const params = {
    volunteerId: dragItem.volunteerId,
    afterSort: newIndex + 1,
  };
  await volunteerSort(params);
};

let currentCollegeItem = null;
const pickMajorDialogVisible = ref(false);
const handleChildrenAddClick = (_item) => {
  currentCollegeItem = _item;
  pickMajorDialogVisible.value = true;
};

const tooltipStates = reactive({});

const closeAllTooltips = () => {
  Object.keys(tooltipStates).forEach((key) => {
    tooltipStates[key] = false;
  });
};

const handleClickOutside = (event) => {
  if (
    !event.target.closest('.tooltip-content') &&
    !event.target.closest('.question-icon')
  ) {
    closeAllTooltips();
  }
};

const showTooltip = (index, itemId) => {
  const key = `${itemId}-${index}`;
  tooltipStates[key] = !tooltipStates[key];
  // 关闭其他所有tooltip
  Object.keys(tooltipStates).forEach((k) => {
    if (k !== key) {
      tooltipStates[k] = false;
    }
  });
};

const handleSetTop = (item, index) => {
  if (index === 0) return; // 已经在最顶，无需操作

  // 标记动画
  item.isMovingToTop = true;

  // 动画持续时间（和CSS动画时间一致）
  setTimeout(() => {
    // 1. 移动到第一个位置
    schoolList.value.splice(index, 1);
    schoolList.value.unshift(item);
    // 2. 移除动画标记
    item.isMovingToTop = false;
    // 3. 调用排序接口
    onFirstLevelEnd({ newIndex: 0 });
  }, 400); // 400ms，和CSS动画时间一致
};

const handleSonSetTop = async (_item, _index, fatherItem) => {
  if (_index === 0) return; // 已经在最顶，无需操作

  _item.isMovingToTop = true;

  setTimeout(async () => {
    // 1. 移动到第一个位置
    fatherItem.children.splice(_index, 1);
    fatherItem.children.unshift(_item);
    // 2. 移除动画标记
    _item.isMovingToTop = false;
    // 3. 调用排序接口
    await onSonLevelDragEnd({ newIndex: 0 }, fatherItem);
  }, 400); // 400ms，和CSS动画时间一致
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});

defineExpose({
  closeAllTooltips,
  getVolunteerGroupListFn,
});
</script>

<style scoped lang="scss">
.volunteerList-wrapper {
  background-color: #fff;
  border-radius: 20px 20px 0px 0px;
  overflow: hidden;
  .header {
    display: flex;
    align-items: center;
    background: #f4f4f4;
    padding: 9px 0;
    .header-item {
      box-sizing: border-box;
      font-size: 22px;
      color: #666;
      font-weight: 400;
      line-height: 22px;
      &.item0 {
        width: 5%;
        text-align: center;
        padding: 0 0 0 0;
      }
      &.item1 {
        width: 7%;
        text-align: left;
        padding: 0 0 0 24px;
        flex-shrink: 0;
      }
      &.item2 {
        width: 32%;
        text-align: left;
        padding: 0 0 0 24px;
      }
      &.item3 {
        width: 9%;
        text-align: center;
      }
      &.item4 {
        width: 15%;
        text-align: right;
        padding: 0 18px 0 0;
      }
      &.item5 {
        width: 8%;
        text-align: left;
        padding: 0 0 0 18px;
      }
      &.item6 {
        width: 8%;
        text-align: left;
        padding: 0 0 0 18px;
      }
      &.item7 {
        width: 8%;
        text-align: left;
        padding: 0 0 0 18px;
      }
      &.item8 {
        flex: 1;
        text-align: center;
        padding: 0 0 0 0;
      }
    }
  }
  .table-container {
    .table-item {
      .father-level {
        width: 100%;
        background: #ffffff;
        display: flex;
        flex-direction: row;
        &.extended {
          box-shadow: 0px 2px 4px 0px #b8e7ff;
        }
        .first-column {
          width: 5%;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          color: #333330;
          cursor: pointer;
          .icon {
            margin-top: 10px;
            width: 26px;
            height: 26px;
            transition: transform 0.3s ease;
            transform: rotate(0deg);

            &.rotate {
              transform: rotate(180deg);
            }
          }
          .tips {
            margin-top: 4px;
            font-size: 18px;
            &.active {
              color: $primary-color;
            }
          }
        }
        .second-column {
          width: 7%;
          flex-shrink: 0;
          box-sizing: border-box;
          padding: 0 0 0 24px;
          font-size: 22px;
          color: #222222;
          span {
            font-weight: bold;
            font-size: 34px;
            color: #222222;
            margin-left: 3px;
            font-family: D-DIN-PRO-600-SemiBold;
          }
          .center-span {
            margin-left: 40px;
            font-weight: bold;
            font-size: 26px;
            color: #222222;
            margin-top: 75px;
          }
          .question {
            font-weight: bold;
            font-size: 22px;
            color: #222222;
            font-family: D-DIN-PRO-600-SemiBold;
          }
          .label {
            width: 40px;
            height: 38px;
            color: #ffffff;
            font-size: 18px;
            font-weight: bold;
            display: flex;
            flex-direction: row;
            justify-content: center;
            padding-top: 6px;
            margin-bottom: 18px;
          }
          .match-rate-bg {
            background-size: 100% 100%;
            background-repeat: no-repeat;
            background-position: center;

            &.high {
              background-image: url(https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/green_bg.png);
            }

            &.medium {
              background-image: url(https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/yellow_bg.png);
            }

            &.low {
              background-image: url(https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/red_bg.png);
            }
          }
          .triangle-down {
            width: 0;
            height: 0;
            border-left: 13px solid transparent;
            border-right: 13px solid transparent;
            border-top: 12px solid transparent; /* 初始颜色为透明 */
            margin-bottom: 6px;
          }
          .risk {
            margin-top: 13px;
            font-weight: 400;
            font-size: 20px;
            color: #777777;
          }
        }
        .third-column {
          width: 32%;
          box-sizing: border-box;
          padding: 24px 0 0 18px;
          .top {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 8px;
            .school-avator {
              width: 28px;
              height: 28px;
              border-radius: 50%;
            }
            .name {
              font-family: PingFang-SC, PingFang-SC;
              font-weight: bold;
              font-size: 26px;
              color: #000000;
              line-height: 28px;
            }
          }
          .middle {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 20px;
            line-height: 20px;
            color: #666;
            white-space: nowrap; /* 禁止换行 */
            overflow: hidden; /* 超出部分隐藏 */
            text-overflow: ellipsis; /* 超出部分显示省略号 */
            margin-top: 20px;
          }
          .bottom {
            margin-top: 12px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 20px;
            color: #666;
            span {
              margin: 0 13px;
            }
          }
        }
        .fourth-column {
          width: 9%;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .num {
            span {
              font-family: D-DIN-PRO-600-SemiBold;
              font-size: 24px;
              color: #222222;
              font-weight: bold;
            }
            font-size: 16px;
          }
          .subject {
            font-weight: 400;
            font-size: 20px;
            color: #666;
            margin-top: 20px;
          }
        }
        .fifth-column {
          width: 15%;
          box-sizing: border-box;
          padding: 8px 14px 8px 0;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          color: #666;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 20px;
          cursor: pointer;
          .fifth-column-item {
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-top: 14px;
            &:first-child {
              margin-top: 0;
            }
            img {
              width: 14px;
              height: 14px;
              margin-left: 4px;
              cursor: pointer;
            }
          }
        }
        .sixth-column,
        .seventh-column,
        .eighth-column {
          width: 8%;
          box-sizing: border-box;
          padding: 8px 14px 8px 18px;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: space-evenly;
          color: #222222;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 20px;
          .sixth-column-item,
          .seventh-column-item,
          .eighth-column-item {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            margin-top: 14px;
            &:first-child {
              margin-top: 0;
            }
            img {
              width: 14px;
              height: 14px;
            }
          }
          .no-data {
            color: #999999;
          }
        }
        .ninth-column {
          user-select: none;
          flex: 1;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          .ninth-column-item {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 10px;
            font-size: 20px;
            color: #999999;
            .icon {
              margin-right: 12px;
              width: 28px;
              height: 28px;
            }
          }
        }
      }
      .son-level {
        width: 100%;
        background: #f3fbff;
        display: flex;
        flex-direction: row;
        box-sizing: border-box;
        .first-column {
          width: 5%;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 22px;
          color: #333330;
        }
        .second-column {
          width: 7%;
          flex-shrink: 0;
          box-sizing: border-box;
          padding: 0 0 18px 24px;
          font-size: 20px;
          color: #222222;
          span {
            font-weight: bold;
            font-size: 34px;
            color: #222222;
            margin-left: 3px;
            font-family: D-DIN-PRO-600-SemiBold;
          }
          .center-span {
            margin-left: 40px;
            font-weight: bold;
            font-size: 26px;
            color: #222222;
            margin-top: 75px;
          }
          .question {
            font-weight: bold;
            font-size: 24px;
            color: #222222;
            font-family: D-DIN-PRO-600-SemiBold;
          }
          .label {
            margin-top: 28px;
            width: 40px;
            height: 38px;
            color: #ffffff;
            font-size: 18px;
            font-weight: bold;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 18px;
            &.success {
              background-color: #08c687;
            }
            &.warning {
              background-color: #ff9e3b;
            }
            &.danger {
              background-color: #f75a3e;
            }
          }
          .risk {
            margin-top: 13px;
            font-weight: 400;
            font-size: 20px;
            color: #777777;
          }
        }
        .third-column {
          width: 32%;
          box-sizing: border-box;
          padding: 30px 18px 0 18px;
          .top {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 8px;
            .name {
              font-family: PingFang-SC, PingFang-SC;
              font-weight: bold;
              font-size: 26px;
              color: #000000;
              line-height: 28px;
            }
          }
          .middle {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 20px;
            line-height: 20px;
            color: #777777;
            margin-top: 20px;
            // 超出两行显示省略号
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          .bottom {
            font-weight: bold;
            font-size: 20px;
            line-height: 20px;
            color: #222222;
            margin-top: 20px;
            // 超出两行显示省略号
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
        }
        .fourth-column {
          width: 9%;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .num {
            span {
              font-family: D-DIN-PRO-600-SemiBold;
              font-size: 26px;
              color: #222222;
              font-weight: bold;
            }
            font-size: 15px;
          }
          .subject {
            font-weight: 400;
            font-size: 18px;
            color: #777777;
            margin-top: 20px;
          }
        }
        .fifth-column {
          width: 15%;
          box-sizing: border-box;
          padding: 8px 14px 8px 0;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          color: #999999;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 20px;
          .fifth-column-item {
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-top: 14px;
            &:first-child {
              margin-top: 0;
            }
            img {
              width: 14px;
              height: 14px;
              margin-left: 4px;
              cursor: pointer;
            }
          }
        }
        .sixth-column,
        .seventh-column,
        .eighth-column {
          width: 8%;
          box-sizing: border-box;
          padding: 8px 14px 8px 18px;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: space-evenly;
          color: #222222;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 20px;
          .sixth-column-item,
          .seventh-column-item,
          .eighth-column-item {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            margin-top: 14px;
            &:first-child {
              margin-top: 0;
            }
            img {
              width: 14px;
              height: 14px;
            }
          }
          .no-data {
            color: #999999;
          }
        }
        .ninth-column {
          user-select: none;
          flex: 1;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 10px;
          .ninth-column-item {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 10px;
            font-size: 20px;
            color: #999999;
            .icon {
              margin-right: 12px;
              width: 28px;
              height: 28px;
            }
          }
        }
      }
      .no-border {
        border: none;
      }
      .add-level {
        width: 100%;
        height: 84px;
        background: #ffffff;
        display: flex;
        flex-direction: row;
        box-sizing: border-box;
        &.add-son {
          background: #f3fbff;
          .index-column {
            font-size: 20px;
            color: #777777;
          }
        }
        .index-column {
          width: 5%;
          height: 100%;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          color: #333330;
          cursor: pointer;
        }
        .add-column {
          display: flex;
          align-items: center;
          justify-content: center;
          flex: 1;
          .add-column-item {
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 22px;
            color: $primary-color;
            padding: 9px 63px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .border-primary {
    border: 1px solid $primary-color;
  }
  .border-left {
    border-left: 1px solid #e7e7e7;
  }
  .border-top {
    border-top: 1px solid #e7e7e7;
  }
  .border-bottom {
    border-bottom: 1px solid #e7e7e7;
  }
  .border-right {
    border-right: 1px solid #e7e7e7;
  }
}
.tooltip-wrapper {
  position: relative;
  .question-icon {
    width: 14px;
    height: 14px;
    margin-left: 2px;
    cursor: pointer;
  }
  .tooltip-content {
    font-size: 22px;
    width: 220px;
    padding: 12px 24px;
    position: absolute;
    top: 18px;
    left: 18px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
    color: #333;
  }
}
// 添加slide过渡动画样式
.slide-enter-active,
.slide-leave-active {
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  overflow: hidden;
}

.slide-enter-from {
  opacity: 0;
  transform: translateY(-20px);
  max-height: 0;
}

.slide-enter-to {
  opacity: 1;
  transform: translateY(0);
  max-height: 1000px; // 设置一个足够大的值
}

.slide-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 1000px;
}

.slide-leave-to {
  opacity: 0;
  transform: translateY(-20px);
  max-height: 0;
}

.father-level.moving-to-top {
  animation: moveToTop 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  z-index: 2;
  position: relative;
}
@keyframes moveToTop {
  0% {
    transform: translateY(0);
    background: #fffbe6;
  }
  60% {
    transform: translateY(-30px) scale(1.03);
    background: #e6f7ff;
  }
  80% {
    transform: translateY(0) scale(1);
    background: #e6f7ff;
  }
  100% {
    transform: translateY(0) scale(1);
    background: #fff;
  }
}

.son-level.moving-to-top {
  animation: moveToTopSon 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  z-index: 2;
  position: relative;
}
@keyframes moveToTopSon {
  0% {
    transform: translateY(0);
    background: #e6f7ff;
  }
  60% {
    transform: translateY(-20px) scale(1.03);
    background: #fffbe6;
  }
  80% {
    transform: translateY(0) scale(1);
    background: #fffbe6;
  }
  100% {
    transform: translateY(0) scale(1);
    background: #f3fbff;
  }
}
</style>
